package com.situ.allaia.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.allaia.dao.UserDao;
import com.situ.allaia.model.AdminUser;
import com.situ.allaia.model.User;
import com.situ.allaia.model.UserSearchBean;
import com.situ.allaia.service.UserService;
import com.situ.allaia.util.PaginateInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImp implements UserService {
    private final UserDao userDao;

    public UserServiceImp(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public List<User> findAll(UserSearchBean usb, PaginateInfo pi) {
        PageHelper.startPage(pi.getPageNo(),pi.getPageSize());
        List<User> result = userDao.findAll(usb);
        //获取分页数据
        PageInfo<User> p = new PageInfo<>(result);
        pi.setTotal(p.getTotal());
        return result;
    }

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public boolean save(User user) {
        String encrypt = user.getPassword() + "{"+user.getUsername()+"}";
        encrypt = DigestUtils.md5DigestAsHex(encrypt.getBytes(StandardCharsets.UTF_8));
        user.setPassword(encrypt);
        System.out.println(user);
        return userDao.save(user)>0;
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public boolean update(User user) {
        String encrypt = user.getPassword() + "{" + user.getUsername() + "}";
        encrypt = DigestUtils.md5DigestAsHex(encrypt.getBytes(StandardCharsets.UTF_8));
        user.setPassword(encrypt);
        return userDao.update(user)>0;
    }

    @Override
    public int deleteByIds(Integer[] ids) {
        return userDao.deleteByIds(ids);
    }
}
